<?php 
namespace app\admin\controller;
use think\Controller;
use catetree\Catetree;

class Cate extends Controller{

	public function index(){
		$cate=new Catetree();
		$cateObj=db('cate');
		if(request()->isPost()){
			$data=input('post.');
			$cate->cateSort($data,$cateObj);
			$this->success('分类排序成功！',url('admin/Cate/index'));
		}
		$cateRes=$cateObj->order("sort asc")->select();
		$cateRes=$cate->catetree($cateRes);
		$this->assign([
			'cateRes'	=>$cateRes,
		]);
		return view();
	}

	public function add(){
		$cate=new Catetree();
		$cateObj=db('cate');
		if(request()->isPost()){
			$data=input('post.');
			if($data){
				$validate=validate('cate');
				if(!$validate->check($data)){
					$this->error($validate->getError());
				}
				$res=$cateObj->insert($data);
				if($res){
					$this->success('分类添加成功！',url('index'));
				}else{
					$this->error('分类添加失败！');
				}
			}
		}
		$cateRes=$cateObj->select();
		$cateRes=$cate->catetree($cateRes);
		$this->assign([
			'cateRes'	=>$cateRes,
		]);
		return view();
	}

	public function edit($id){
		$cate = new Catetree();
		$cateobj = db('cate');
		if(request()->isPost()){
			$data=input('post.');
			$data_res=$cateobj->update($data);
			if($data_res !== false){
				$this->success('分类修改成功！',url('admin/Cate/index'));
			}else{
				$this->error('分类修改失败！');
			}
		}
		$idres=$cateobj->find($id);
		$cateRes = $cateobj->select();
		$cateRes = $cate->catetree($cateRes);
		$this->assign([
			'cateRes'	=>$cateRes,
			'idres'		=>$idres,
		]);
		return view();
	}

	public function del($id){
		$cate = new Catetree();
		$cateobj = db('cate');
		$son_ids=$cate->childrenids($id,$cateobj);
		$son_ids[] = intval($id);
		$article = db('article');
		foreach($son_ids as $k=>$v){
			$artRes=$article->field('id,thumb')->where(array('cate_id'=>$v))->select();
			foreach ($artRes as $k1 => $v1) {
                $thumbSrc=IMG_UPLOAD.$v1['thumb'];
                if(file_exists($thumbSrc)){
                    @unlink($thumbSrc);
                }
                $article->delete($v1['id']);
            }
		}
		$d_res = $cateobj->delete($son_ids);
		if($d_res){
			$this->success('分类删除成功！',url('admin/Cate/index'));
		}else{
			$this->erro('分类删除失败！');
		}
	}
}